
from models.user_models import Patient, Account, UserType
from fastapi import APIRouter,Depends,Request, HTTPException
from sqlalchemy.orm import Session
from pydantic import BaseModel
from jose import jwt, JWTError
from datetime import datetime, timedelta, timezone
from models.user_models import Patient,Account


from typing import Optional


from config import *

router = APIRouter()




# 验证token
def verify_token(token: str, db: Session):
    try:
        # 解码 token 并验证有效性
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        user_id = payload.get("sub")
        user_type = UserType(payload.get("user_type"))

        if user_id is None:
            raise HTTPException(status_code=401, detail="Invalid token")

        # 查找用户
        user = db.query(Patient).filter(Patient.ID == user_id).first()
        if user is None:
            raise HTTPException(status_code=401, detail="User not found")

        user.user_type = user_type
        return user

    except JWTError:
        raise HTTPException(status_code=401, detail="Invalid token")


def get_token_payload(request: Request) -> dict:
    auth_header: Optional[str] = request.headers.get("Authorization")
    if not auth_header or not auth_header.startswith("Bearer "):
        raise HTTPException(status_code=401, detail="Missing or invalid token")

    token = auth_header.split(" ")[1]
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        print(payload)
    except JWTError:
        raise HTTPException(status_code=401, detail="Invalid token")

    if datetime.fromtimestamp(payload.get("exp"), tz=timezone.utc) < datetime.now(timezone.utc):
        raise HTTPException(status_code=401, detail="Token expired")

    return payload

# 检测用户类型是否在列表中
def require_user(*allowed_types: UserType):
    def _verify(payload: dict = Depends(get_token_payload)):
        # 将 user_type 字符串转换为枚举类型
        user_type=UserType.from_str(payload.get("user_type"))

        # 如果 user_type 无效或者不在允许的类型中，则抛出权限异常
        if not user_type or user_type not in allowed_types:
            raise HTTPException(status_code=403, detail="Permission denied")

        return payload

    return _verify

# 使用 ：
# 添加 user=Depends(require_user(UserType.ADMIN, UserType.PATIENT)) 到路由函数的参数中
# 单个用户类型 user=Depends(require_user(UserType.ADMIN))